﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;

namespace HamcoWcs.Service.Common
{
    public class MysqlHelper
    {
        public static string ExportDb(string dbName, IEnumerable<string> tables)
        {
            if (tables?.Count() > 0)
            {
                StringBuilder commandinfo = new StringBuilder();
                string directory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"log{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.sql");//导出sql文件存储的路径
                commandinfo.AppendFormat($"mysqldump -uroot -p123456 --databases {dbName} --tables {string.Join(" ", tables)} > {directory}");//3306-端口号、111111-数据库等密码、test-我的数据库名称
                String exportCommand = commandinfo.ToString();


                String mysqldumpDirecroty = @"C:\Program Files\MySQL\MySQL Server 5.7\bin";

                Process p = new Process();
                p.StartInfo.FileName = "cmd.exe";
                p.StartInfo.WorkingDirectory = mysqldumpDirecroty;
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.RedirectStandardInput = true;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.RedirectStandardError = true;
                p.StartInfo.CreateNoWindow = true;
                p.Start();
                p.StandardInput.WriteLine(exportCommand);
                p.StandardInput.WriteLine("exit");

                Thread.Sleep(1000);

                return directory;
            }
            else
            {
                throw new Exception("tables is null");
            }

        }
    }
}
